<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="XG_J8ModD9lm1c0KqNVAQ3XvUfIQFhmYZgdxyeUFxVI" />







  <meta name="baidu-site-verification" content="BYxasfLxtf" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="IOS," />





  <link rel="alternate" href="/atom.xml" title="Kieran" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="__attribute__ 是一个编译器指令，规定了声明的特性，这就有更多的错误检查和先进的优化的方法。开发者可以向编译器表达某种要求，比如 静态分析器，名字重名，代码生成等过程，一般格式 __attribute__(xxx)格式，常用的属性Cocoa 定义成了宏，比如 NS_CLASS_AVAILABLE_IOS(9_0) 通过 `attribute(warn_unused_result(…)定">
<meta name="keywords" content="IOS">
<meta property="og:type" content="article">
<meta property="og:title" content="IOS Clang Attributes 属性">
<meta property="og:url" content="http://kieran.cn/2017/06/26/IOS-Clang-Attributes/index.html">
<meta property="og:site_name" content="Kieran">
<meta property="og:description" content="__attribute__ 是一个编译器指令，规定了声明的特性，这就有更多的错误检查和先进的优化的方法。开发者可以向编译器表达某种要求，比如 静态分析器，名字重名，代码生成等过程，一般格式 __attribute__(xxx)格式，常用的属性Cocoa 定义成了宏，比如 NS_CLASS_AVAILABLE_IOS(9_0) 通过 `attribute(warn_unused_result(…)定">
<meta property="og:updated_time" content="2017-06-26T06:50:24.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="IOS Clang Attributes 属性">
<meta name="twitter:description" content="__attribute__ 是一个编译器指令，规定了声明的特性，这就有更多的错误检查和先进的优化的方法。开发者可以向编译器表达某种要求，比如 静态分析器，名字重名，代码生成等过程，一般格式 __attribute__(xxx)格式，常用的属性Cocoa 定义成了宏，比如 NS_CLASS_AVAILABLE_IOS(9_0) 通过 `attribute(warn_unused_result(…)定">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://kieran.cn/2017/06/26/IOS-Clang-Attributes/"/>





  <title>IOS Clang Attributes 属性 | Kieran</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Kieran</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://kieran.cn/2017/06/26/IOS-Clang-Attributes/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kieran zhi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Kieran">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">IOS Clang Attributes 属性</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-26T09:53:00+08:00">
                2017-06-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/IOS/" itemprop="url" rel="index">
                    <span itemprop="name">IOS</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/2017/06/26/IOS-Clang-Attributes/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          
          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><code>__attribute__</code> 是一个编译器指令，规定了声明的特性，这就有更多的错误检查和先进的优化的方法。开发者可以向编译器表达某种要求，比如 静态分析器，名字重名，代码生成等过程，一般格式 <code>__attribute__(xxx)</code>格式，常用的属性Cocoa 定义成了宏，比如 NS_CLASS_AVAILABLE_IOS(9_0) 通过 `<strong>attribute</strong>(warn_unused_result(…)定义的，用到的属性是 warn_unused_result，下面是集中常用的属性：</p>
<h3 id="objc-subclassing-restricted"><a href="#objc-subclassing-restricted" class="headerlink" title="objc_subclassing_restricted"></a>objc_subclassing_restricted</h3><p>这个属性可以定义一个太监类，一个不可以被继承的类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">__attribute__((objc_subclassing_restricted))</div><div class="line">@interface Eunuch : NSObject</div><div class="line">@end</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">@interface Child : Eunuch // &lt;--- 编译会报错,Cannot subclass a class with objc_subclassing_restricted attribute</div><div class="line">@end</div></pre></td></tr></table></figure>
<h3 id="warn-unused-result-constructor"><a href="#warn-unused-result-constructor" class="headerlink" title="warn_unused_result constructor"></a>warn_unused_result constructor</h3><p>这个属性声明 子类调用这个方法必须调用super，否则给出编译警告，使用方法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">@interface TestObject : NSObject</div><div class="line">- (void)testMethod __attribute__((objc_requires_super));</div><div class="line">@end</div><div class="line"></div><div class="line">@implementation TestObject</div><div class="line">- (void)testMethod &#123;</div><div class="line">    NSLog(@&quot;hail testMethod!&quot;);</div><div class="line">&#125;</div><div class="line">    </div><div class="line">@end</div><div class="line"></div><div class="line">@interface ChildObject : TestObject</div><div class="line">@end</div><div class="line">@implementation ChildObject</div><div class="line"></div><div class="line">- (void)testMethod &#123;</div><div class="line">&#125; // &lt;--- 编译会警告，Method possibly missing a [super testMethod] call</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
<h3 id="objc-boxable"><a href="#objc-boxable" class="headerlink" title="objc_boxable"></a>objc_boxable</h3><p>这个属性可以将  struct 或者union 转换成 NSValue</p>
<blockquote>
<p>Objective-C 可以使用 @(…)<code>@(1.1)</code> 转换成 NSNumber 对象，如果想让 struct 或者union 转换成 NSValue，可以使用这个属性</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">typedef struct __attribute__((objc_boxable)) &#123;</div><div class="line">    CGFloat x, y, width, height;</div><div class="line">&#125; XXRect;</div><div class="line"></div><div class="line">- (void)testmethod&#123;</div><div class="line">    CGRect rect1 = &#123;1.0,1.0,1.0,1.0&#125;;</div><div class="line">    XXRect rect2 = &#123;1.0,1.0,1.0,1.0&#125;;</div><div class="line"></div><div class="line">    NSValue *value1 = @(rect1); // &lt;--- 编译报错 ，Illegal type &apos;CGRect&apos; (aka &apos;struct CGRect&apos;) used in a boxed expression</div><div class="line">    NSValue *value2 = @(rect2); </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="constructor-destructor"><a href="#constructor-destructor" class="headerlink" title="constructor/destructor"></a>constructor/destructor</h3><p>构造器和解析器，加上这两个属性的函数会在加载可以执行文件（或者shared library） load 和 unload 时候调用，可以理解为 在main() 函数开始前调用，后return 后调用。也可以理解为constructor程序启动的时候调用，destructor 在程序杀死或退出时候调用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">int main(int argc, char * argv[]) &#123;</div><div class="line">    @autoreleasepool &#123;</div><div class="line">        NSLog(@&quot;main&quot;);</div><div class="line">        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">__attribute__((constructor))</div><div class="line">static void beforeMain() &#123;</div><div class="line">    </div><div class="line">    NSLog(@&quot;beforeMain&quot;);</div><div class="line">&#125;</div><div class="line">    </div><div class="line">__attribute__((destructor))</div><div class="line">static void afterMain() &#123;</div><div class="line">    NSLog(@&quot;afterMain&quot;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>+load 方法回比constructor更加早执行，因为dyld（动态库）加载image（mach-o）会通知runtime 去加载其中所有的类，每个类加载的时候，所对应的load 方法随之调用，全部加载完成后，dyld 才会调用这个 image 中所有的 constructor 方法。若有多个 constructor 且想控制优先级的话，可以写成 <code>__attribute__((constructor(101)))</code>，里面的数字越小优先级越高，1 ~ 100 为系统保留。</p>
</blockquote>
<p>所以 constructor 是一个干坏事的绝佳时机：</p>
<ol>
<li>所有 Class 都已经加载完成</li>
<li>main 函数还未执行</li>
<li>无需像 +load 还得挂载在一个 Class 中<br>FDStackView 的 FDStackViewPatchEntry 方法便是使用的这个时机来实现偷天换日的伎俩。</li>
</ol>
<h3 id="enable-if"><a href="#enable-if" class="headerlink" title="enable_if"></a>enable_if</h3><p>这个属性只能用在 C 函数上，可以用来实现参数的静态检查：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">static void printValidAge(int age)</div><div class="line">__attribute__((enable_if(age &gt; 0 &amp;&amp; age &lt; 120, &quot;你丫火星人？&quot;))) &#123;</div><div class="line">    printf(&quot;%d&quot;, age);</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>它表示调用这个函数时必须满足 age &gt; 0 &amp;&amp; age &lt; 120 才被允许，于是乎：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">printValidAge(26); // √</div><div class="line">printValidAge(150); // &lt;--- Compile Error</div><div class="line">printValidAge(-1); // &lt;--- Compile Error</div></pre></td></tr></table></figure>
<h3 id="cleanup"><a href="#cleanup" class="headerlink" title="cleanup"></a>cleanup</h3><p>用于修饰一个变量，在它的作用域结束时可以自动执行一个指定的方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">// 指定一个cleanup方法，注意入参是所修饰变量的地址，类型要一样</div><div class="line">// 对于指向objc对象的指针(id *)，如果不强制声明__strong默认是__autoreleasing，造成类型不匹配</div><div class="line">static void stringCleanUp(__strong NSString **string) &#123;</div><div class="line">    NSLog(@&quot;%@&quot;, *string);</div><div class="line">&#125;</div><div class="line">// 在某个方法中：</div><div class="line">- (void)test&#123;</div><div class="line">    __strong NSString *string __attribute__((cleanup(stringCleanUp))) = @&quot;sunnyxx&quot;;</div><div class="line">&#125; // 当运行到string作用域结束时，自动调用stringCleanUp</div></pre></td></tr></table></figure>
<p>作用域结束，包括大括号结束、return、goto、break、exception等各种情况。<br>当然，可以修饰的变量不止NSString，自定义Class或基本类型都是可以的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">// 自定义的Class</div><div class="line">static void sarkCleanUp(__strong Sark **sark) &#123;</div><div class="line">    NSLog(@&quot;%@&quot;, *sark);</div><div class="line">&#125;</div><div class="line">__strong Sark *sark __attribute__((cleanup(sarkCleanUp))) = [Sark new];</div><div class="line">// 基本类型</div><div class="line">static void intCleanUp(NSInteger *integer) &#123;</div><div class="line">    NSLog(@&quot;%d&quot;, *integer);</div><div class="line">&#125;</div><div class="line">NSInteger integer __attribute__((cleanup(intCleanUp))) = 1;</div></pre></td></tr></table></figure>
<blockquote>
<p>一个作用域内有若干个cleanup的变量，他们的调用顺序是先入后出的栈式顺序； 而且，cleanup是先于这个对象的dealloc调用的。</p>
</blockquote>
<p>用于修饰一个block<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">static void blockCleanUp(__strong void(^*block)(void)) &#123;</div><div class="line">    (*block)();</div><div class="line">&#125;</div><div class="line">#define onExit\</div><div class="line">    __strong void(^block)(void) __attribute__((cleanup(blockCleanUp), unused)) = ^</div><div class="line">    </div><div class="line">    </div><div class="line">- (void)testOnExit&#123;</div><div class="line">    NSLock *aLock = [[NSLock alloc] init];</div><div class="line">    [aLock lock];</div><div class="line">    onExit&#123;</div><div class="line">        [lock unlock];</div><div class="line">        NSLog(@&quot;方法已经执行完成&quot;);</div><div class="line">    &#125;;</div><div class="line">    //</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="overloadable"><a href="#overloadable" class="headerlink" title="overloadable"></a>overloadable</h3><p>用于 C 函数，可以定义若干个函数名相同，但参数不同的方法，调用时编译器会自动根据参数选择函数原型：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">__attribute__((overloadable)) void logAnything(id obj) &#123;</div><div class="line">    NSLog(@&quot;%@&quot;, obj);</div><div class="line">&#125;</div><div class="line">__attribute__((overloadable)) void logAnything(int number) &#123;</div><div class="line">    NSLog(@&quot;%@&quot;, @(number));</div><div class="line">&#125;</div><div class="line">__attribute__((overloadable)) void logAnything(CGRect rect) &#123;</div><div class="line">    NSLog(@&quot;%@&quot;, NSStringFromCGRect(rect));</div><div class="line">&#125;</div><div class="line">// Tests</div><div class="line">logAnything(@[@&quot;1&quot;, @&quot;2&quot;]);</div><div class="line">logAnything(233);</div><div class="line">logAnything(CGRectMake(1, 2, 3, 4));</div></pre></td></tr></table></figure>
<h3 id="objc-runtime-name"><a href="#objc-runtime-name" class="headerlink" title="objc_runtime_name"></a>objc_runtime_name</h3><p>可以吧 <code>@interface</code> 或 <code>@protocol</code>，将类或协议的名字在编译时指定成另一个：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">__attribute__((objc_runtime_name(&quot;SarkGay&quot;)))</div><div class="line">@interface Sark : NSObject</div><div class="line">@end</div><div class="line"></div><div class="line">NSLog(@&quot;%@&quot;, NSStringFromClass([Sark class])); // &quot;SarkGay&quot;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>直接使用这个类名的地方都会被替换（唯一要注意的是这时用反射就不对了），最简单粗暴的用处就是去做个类名混淆：</p>
</blockquote>
<h3 id="format"><a href="#format" class="headerlink" title="format"></a>format</h3><p>格式化字符串<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">//意思是第二个参数my_format参数是二个格式化字符串，从第三个参数开始检查</div><div class="line">extern int my_printf (void *my_object, const char *my_format, ...) __attribute__((format(printf, 2, 3)))</div></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">意思是第二个参数my_format参数是一个格式化字符串，从第二个参数开始检查</div><div class="line">FOUNDATION_EXPORT void NSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2) NS_NO_TAIL_CALL;</div></pre></td></tr></table></figure>
<h3 id="deprecated"><a href="#deprecated" class="headerlink" title="deprecated"></a>deprecated</h3><p>定义被弃用的方法或属性</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">//标识改方法已经弃用</div><div class="line">- (void)preMethod:(NSString *)string __attribute__((deprecated(&quot;preMethod已经被弃用，请使用newMethod&quot;)));</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">@property(nonatomic,strong) NSString * variable __attribute__((deprecated(&quot;preMethod已经被弃用，请使用newMethod&quot;)));</div></pre></td></tr></table></figure>
<h3 id="warn-unused-result"><a href="#warn-unused-result" class="headerlink" title="warn_unused_result"></a>warn_unused_result</h3><p><code>attribute((availability(os,introduced=m,deprecated=n, obsoleted=o,message=&quot;&quot; VA_ARGS)))</code> 指明使用版本范围</p>
<p>os 指系统的版本，m 指明引入的版本，n 指明过时的版本，o 指完全不用的版本，message 可以写入些描述信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (void)method __attribute__((availability(ios,introduced=3_0,deprecated=6_0,obsoleted=7_0,message=&quot;iOS3到iOS7版本可用，iOS7不能用&quot;)));</div></pre></td></tr></table></figure>
<h3 id="unavailable"><a href="#unavailable" class="headerlink" title="unavailable"></a>unavailable</h3><p>这个会在编译过程中告知方法不可用，如果使用了还会让编译失败。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (void)method __attribute__((unavailable(&quot;该方法不可用&quot;)))</div></pre></td></tr></table></figure>
<h3 id="unused"><a href="#unused" class="headerlink" title="unused"></a>unused</h3><p>没有使用也不报警告</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">NSString * variable __attribute__((unused));</div><div class="line">//没有调用也不会报警告    </div><div class="line">- (void)testmethod __attribute__((unused));</div></pre></td></tr></table></figure>
<h3 id="objc-designated-initializer"><a href="#objc-designated-initializer" class="headerlink" title="objc_designated_initializer"></a>objc_designated_initializer</h3><p>用于声明初始化方法，必须以<code>- (id)initTXXX</code> 方法开头。</p>
<ul>
<li><p>如果是 objc_designated_initializer 初始化的方法必须调用覆盖实现 super 的 objc_designated_initializer 方法。</p>
</li>
<li><p>如果不是 objc_designated_initializer 的初始化方法，但是该类有 objc_designated_initializer 的初始化方法，那么必须调用该类的 objc_designated_initializer 方法或者非 objc_designated_initializer 方法，而不能够调用 super 的任何初始化方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (id)initMethod __attribute__((objc_designated_initializer));</div></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="const"><a href="#const" class="headerlink" title="const"></a>const</h3><p>用于数值类型参数的函数，多次调用相同的数值型参数，返回是相同的，只在第一次是需要进行运算，后面只返回第一次的结果，这时编译器的一种优化处理方式。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/IOS/" rel="tag"># IOS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/24/Git-多SSH-Key/" rel="next" title="AutomatorX 使用">
                <i class="fa fa-chevron-left"></i> AutomatorX 使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Kieran zhi" />
          <p class="site-author-name" itemprop="name">Kieran zhi</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/kyios" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.baidu.com/" title="百度" target="_blank">百度</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://example.com/" title="新浪" target="_blank">新浪</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#objc-subclassing-restricted"><span class="nav-number">1.</span> <span class="nav-text">objc_subclassing_restricted</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#warn-unused-result-constructor"><span class="nav-number">2.</span> <span class="nav-text">warn_unused_result constructor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#objc-boxable"><span class="nav-number">3.</span> <span class="nav-text">objc_boxable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#constructor-destructor"><span class="nav-number">4.</span> <span class="nav-text">constructor/destructor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#enable-if"><span class="nav-number">5.</span> <span class="nav-text">enable_if</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cleanup"><span class="nav-number">6.</span> <span class="nav-text">cleanup</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#overloadable"><span class="nav-number">7.</span> <span class="nav-text">overloadable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#objc-runtime-name"><span class="nav-number">8.</span> <span class="nav-text">objc_runtime_name</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#format"><span class="nav-number">9.</span> <span class="nav-text">format</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#deprecated"><span class="nav-number">10.</span> <span class="nav-text">deprecated</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#warn-unused-result"><span class="nav-number">11.</span> <span class="nav-text">warn_unused_result</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unavailable"><span class="nav-number">12.</span> <span class="nav-text">unavailable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unused"><span class="nav-number">13.</span> <span class="nav-text">unused</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#objc-designated-initializer"><span class="nav-number">14.</span> <span class="nav-text">objc_designated_initializer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#const"><span class="nav-number">15.</span> <span class="nav-text">const</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
<div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kieran zhi</span>
<span id="busuanzi_container_site_pv">
本站总访问量<span id="busuanzi_value_site_pv"></span>次
<span id="busuanzi_container_site_uv">
本站访客数<span id="busuanzi_value_site_uv"></span>人次
</span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>




  


  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "9da2e20b42e745e2bfe61eb017fc9832",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
